package com.linewell.license.demo.security;

import com.linewell.license.demo.bean.UserDetail;
import com.linewell.license.demo.service.UserDetailsService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

/**
* @author
* Company:
* Createtime : 2018年9月11日 下午2:37:37
* Description : 自定义认证服务
*/
@Component
public class SecurityAuthenticationProvider implements AuthenticationProvider {
	private Logger logger = LoggerFactory.getLogger(SecurityAuthenticationProvider.class);

	/**
	 * *返回true后才会执行上面的authenticate方法,这步能确保authentication能正确转换类型
	 */
	@Override
	public boolean supports(Class<?> authentication) {
		return UsernamePasswordAuthenticationToken.class.equals(authentication) ;
	}

	@Autowired
	UserDetailsService userDetailsService;

	@Override
	public Authentication authenticate(Authentication authentication) throws AuthenticationException {
		try {
			UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) authentication;
			if (StringUtils.isEmpty(token.getName())) {
				throw new BadCredentialsException("用户名不能为空，请确认");
			}
			if (StringUtils.isEmpty(token.getCredentials())) {
				throw new BadCredentialsException("密码不能为空，请确认");
			}
			UserDetail user = (UserDetail) userDetailsService.loadUserByUsername(token.getName());
			if (user == null) {
				throw new BadCredentialsException("用户不存在，请确认");
			}
			if (!token.getName().equals(user.getUsername())) {
				throw new BadCredentialsException("用户名错误，请确认");
			}
			if (!token.getCredentials().equals(user.getPassword())) {
				throw new BadCredentialsException("密码错误，请确认");
			}
			//授权
			return new UsernamePasswordAuthenticationToken(user, user.getPassword(), user.getAuthorities());
		}catch (BadCredentialsException e){
			throw e;
		}catch (Exception e){
			logger.error(e.getMessage() , e);
			throw new BadCredentialsException("未知错误，请联系管理员");
		}
	}

}
